<template>
  <el-select style="width: 100%" clearable filterable :placeholder="placeholder" v-model="selected" @change="select">
    <el-option v-for="item in dataList" :key="item._id" :label="item.name" :value="item._id" />
  </el-select>
</template>

<script setup lang="ts" name="selectFilter">
import { onMounted, ref } from "vue";
import { Item } from "@/api/types/base";
import apiService from "@/api/services/apiService";

const dataList = ref<Item[]>([]);
const selected = ref<{ [key: string]: any }>({});

interface SelectFilterProps {
  requestApi?: (params: any) => Promise<any>; // 请求表格数据的 api ==> 非必传
  data?: Item[]; // 选择的列表数据
  value?: String;
  placeholder?: String;
}

const props = withDefaults(defineProps<SelectFilterProps>(), {
  placeholder: () => "请选择",
  value: () => ""
});

onMounted(() => {
  selected.value = props.value;
  if (props.data) {
    dataList.value = props.data;
  } else {
    if (props.requestApi) {
      props.requestApi!({}).then(({ data }) => {
        dataList.value = data;
      });
    } else {
      const options = {
        fields: ["_id", "name"],
        sort: {
          name: 1
        }
      };
      apiService.find<Item[]>("item", {}, options).then(({ data }) => {
        dataList.value = data;
      });
    }
  }
});

const select = () => {
  emit("change", selected.value);
};

// emit
const emit = defineEmits<{
  change: [value: any];
}>();
</script>

<style scoped lang="scss"></style>
